<?php
/**
 * 介绍和帮助
 * @author 江羿平<hugcolin@163.com>
 */

use Core\AdminController;
use Models\Help;
class HelpController extends AdminController {

	protected $types = array();

	public function __construct(){
		parent::__construct();
	
		$this->types = CONFIG('basic.help');
	}

	/**
	 * 列表页
	 */
	public function index(){
		$help = new Help;
		$type = $this->input->get('type');
		$keyword = $this->input->get('keyword');
		if($type){
			$help->where('type',$type);
		}
		if($keyword){
			$help->like('title',$keyword);
		}

		$data['helps'] = $help->order_by('id','desc')->paginate(20);
		$data['types'] = $this->types;
		$this->load->view('admin/help/index',$data);
	}

	

	/**
	 * 添加页面
	 */
	public function add(){
		$data['types'] = $this->types;
		$data['back_url'] = $this->input->server('HTTP_REFERER');
		$this->load->view('admin/help/add',$data);
	}

	/**
	 * 编辑页面
	 */
	public function edit($id){
		$data['types'] = $this->types;
		$help = new Help;
		$data['help'] = $help->find(intval($id));
		$data['back_url'] = $this->input->server('HTTP_REFERER');
		$this->load->view('admin/help/add',$data);
	}

	/**
	 * 删除
	 */
	public function delete(){
		$help = new Help;
		$help->delete($this->input->post('id'));
		echo json_encode(array('code'=>0,'msg'=>'ok'));
	}


	/**
	 * 提交保存
	 */
	public function save(){
		
		$data['type'] = $this->input->post('type');
		$data['title'] = $this->input->post('title');
		$data['en_title'] = $this->input->post('en_title');
		$data['content'] = $this->input->post('content');
		$data['en_content'] = $this->input->post('en_content');
		$data['sort'] = intval($this->input->post('sort'))?intval($this->input->post('sort')):0;
		$data['status'] = $this->input->post('status');

		if(!$data['type'] || !$data['title'] || !$data['en_title'] || !$data['content'] || !$data['en_content']){
			
			echo json_encode(array('code'=>2,'msg'=>json_encode($data)));
			exit;
		}

		$help = new Help;
		if(intval($this->input->post('id'))){
			$help->update(intval($this->input->post('id')),$data);
			echo json_encode(array('code'=>0,'msg'=>'ok','help_id'=>$this->input->post('id')));
		}else{
			$data['create_time'] = time();
			$help_id = $help->add($data);
			if($help_id){
				echo json_encode(array('code'=>0,'msg'=>'ok','help_id'=>$help['id']));	
			}else{
				echo json_encode(array('code'=>1));
			}
		}
	}

}
